import { computed, effect } from 'vue';
import { UserInfo } from './UserInfo';
import cloneDeep from 'lodash/cloneDeep';
import router from '@/router/index';
import { constantRoute, _asyncRoute, asyncRoute, anyRoute } from '@/router/routes';

// 这里集中返回整个项目所有的单例模型的地方



// 导出用户信息
export const userInfo = new UserInfo()





// 处理异步路由
const filterUserRoute = (asyncRoute, route) => {

  return asyncRoute.filter(item => {
    if (item.children && item.children.length > 0) {
      // 有子路由的情况
      item.children = filterUserRoute(item.children, route)
      return true
    } else if (route?.includes(item.name)) {
      // 没有子路由的情况
      return true
    }
  })
}


// 导出菜单
export const menu = computed(() => {
  if (userInfo.vm.status !== 2) return []

  const userAsyncRoute = filterUserRoute(cloneDeep(asyncRoute), userInfo.vm.data?.routes)
  // 整合菜单路由，让菜单组件渲染菜单
  return [...constantRoute, ...userAsyncRoute, anyRoute]
})


effect(() => {
  menu.value.forEach((route) => {
    router.addRoute(route)
  })

})

